(function () {
  const LANG_KEY = 'site_lang';
  const DEFAULT_LANG = 'en';
  const SUPPORTED = ['zh', 'en', 'ar', 'es', 'ja', 'ko', 'zh-TW'];

  const $ = (s, r = document) => r.querySelector(s);
  const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));

  function detectInitialLang() {
    const saved = localStorage.getItem(LANG_KEY);
    if (saved && SUPPORTED.includes(saved)) return saved;
    const nav = (navigator.language || navigator.userLanguage || '').toLowerCase();
    if (nav.startsWith('zh')) return 'zh';
    if (nav.startsWith('ar')) return 'ar';
    return 'en';
  }

  function setDirAndHtmlLang(lang) {
    const html = document.documentElement;
    html.lang = lang;
    html.dir = lang === 'ar' ? 'rtl' : 'ltr';
  }

  async function loadLocale(lang) {
    try {
      const res = await fetch(`locales/${lang}.json`, { cache: 'no-cache' });
      if (!res.ok) throw new Error('Locale not found');
      return await res.json();
    } catch (e) {
      console.error('i18n load error:', e);
      if (lang !== DEFAULT_LANG) {
        return loadLocale(DEFAULT_LANG);
      }
      return {};
    }
  }

  function applyI18n(dict) {
    // 文本
    $$('[data-i18n]').forEach(el => {
      const key = el.getAttribute('data-i18n');
      const val = getByPath(dict, key);
      if (val) el.textContent = val;
    });
    // placeholder
    $$('[data-i18n-placeholder]').forEach(el => {
      const key = el.getAttribute('data-i18n-placeholder');
      const val = getByPath(dict, key);
      if (val) el.setAttribute('placeholder', val);
    });
    // 标题或文档title
    const metaTitle = getByPath(dict, 'meta.title');
    if (metaTitle) document.title = metaTitle;
  }

  function getByPath(obj, path) {
    return path.split('.').reduce((o, k) => (o && o[k] != null ? o[k] : null), obj);
  }

  async function switchLang(lang) {
    if (!SUPPORTED.includes(lang)) lang = DEFAULT_LANG;
    const dict = await loadLocale(lang);
    setDirAndHtmlLang(lang);
    applyI18n(dict);
    localStorage.setItem(LANG_KEY, lang);
    const sel = $('#langSwitcher');
    if (sel && sel.value !== lang) sel.value = lang;
  }

  // 初始化
  document.addEventListener('DOMContentLoaded', () => {
    const initial = detectInitialLang();
    switchLang(initial);

    const sel = $('#langSwitcher');
    if (sel) {
      sel.value = initial;
      sel.addEventListener('change', (e) => {
        switchLang(e.target.value);
      });
    }
  });
})();